<?php

/**
 * CelebrioWeather default
 *
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    CelebrioWeather
 */

namespace ApplicationsModule\WeatherModule;

use WebtopModule\BasePresenter;
use Celebrio\WeatherApi\WorldWeatherOnline\LocationNotFoundException;
use Celebrio\WeatherApi\WorldWeatherOnline\ServerNotRespondingException;
use ApplicationsModule\WeatherModule\WeatherModel;

class WeatherPresenter extends BasePresenter {

    private $place = "786869"; //Brno

    public function startup() {
        parent::startup();
        header("Content-type:text/html; charset=utf-8"); // TODO: poresit
    }

    public function renderDefault() {
        $this->getTemplate()->title = _("Weather");
        $this->getTemplate()->appName = "weather";
        $this->template->version = "new";
    }

    public function renderWeather($latitude, $longitude, $place = "") {
        $this->place = $latitude . " : " . $longitude;
        $this->invalidateControl("celebrioweatherappSnippet");
        $this->template->currentTime = date("H:i"); // TODO: nationalize the time
        $this->redrawWeather($latitude, $longitude, $place);
    }

    private function redrawWeather($latitude, $longitude, $place) {
        $this->template->currentTime = date("H:i"); // TODO: nationalize the time
        try {
            $weatherForecast = new WeatherModel($place);
            $weather = $weatherForecast->getForecastClient($latitude, $longitude, $place);
            $data = $weather->getForecast();
            if (isset($data["currentConditions"])) {
                $this->template->currentConditions = $data["currentConditions"];
            }
            if (isset($data["forecast"])) {
                $this->template->forecast = $data["forecast"];
            }
        } catch (ServerNotRespondingException $e) {
            // TODO: log the error and handle error
            return;
        } catch (LocationNotFoundException $e) {
            //TODO: when this occur, data should be taken from cache.
            $this->template->errorLocation = _("City $place was not found");
            return;
        } catch (\InvalidArgumentException $e) {
            //log
            return;
        }
    }

}